package com.zb.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.dto.LoginUser;
import com.zb.entity.TbAdminModel;
import com.zb.exceptions.BussinessException;
import com.zb.mapper.TbAdminMapper;
import com.zb.service.TbAdminService;
import com.zb.util.JwtUtil;
import com.zb.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName TbAdminServiceImpl
 * @Description 服务接口实现
 * @Author xm
 * @Date 2024/08/05 08:51
 **/
@Service
public class TbAdminServiceImpl extends ServiceImpl<TbAdminMapper, TbAdminModel> implements TbAdminService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public R login(String username, String passwd) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, passwd);
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (authenticate == null) {
            throw new BussinessException("用户不存在!");
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String token = JwtUtil.createJWT(loginUser.getUsername());
        redisTemplate.boundValueOps("login:" + loginUser.getUsername()).set(loginUser);
        return new R(200, token);
    }
}
